package com.changgou.seckill.timer;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import entity.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @ClassName SeckillGoodsPushTask
 * @Description 定时任务
 * @Author Mr.L
 * @Date 20:34 2019/11/27
 * @Version 2.1
 **/
@Component
public class SecKillGoodsPushTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    private SeckillGoodsMapper seckillGoodsMapper;

    public SecKillGoodsPushTask() {
    }


    @Scheduled(cron = "0/15 * * * * ?")
    public void pushGoodsToRedis() {
        // 需求：将秒杀商品的数据保存到redis中
        // 获取时间的区间段
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {


            String key_rule = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYYMMDDHH);
            // 查询该区间段下的商品列表：开始时间 结束时间 库存量  审核状态
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andGreaterThanOrEqualTo("startTime", dateMenu);
            criteria.andLessThanOrEqualTo("endTime", DateUtil.addDateHour(dateMenu, 2));
            criteria.andGreaterThan("stockCount", 0);
            criteria.andEqualTo("status", "1");
            // select * from table where startTime >= xxx and endTime <= xxx and stock > 0 and status = 1 and not id in(1,2,3)
            Set ids = redisTemplate.boundHashOps("SeckillGoods_" + key_rule).keys();
            if (ids != null && ids.size() > 0) {
                criteria.andNotIn("id", ids);
            }

            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectByExample(example);

            System.out.println("查询的个数：" + seckillGoodsList.size());

            // 将商品保存到redis中：hash  hset  key  field  value
            if (seckillGoodsList != null && seckillGoodsList.size() > 0) {
                for (SeckillGoods seckillGoods : seckillGoodsList) {
                    redisTemplate.boundHashOps("SeckillGoods_" + key_rule).put(seckillGoods.getId(), seckillGoods);

                    // 获取当前商品的id个数
                    Long[] idArrays = pushId(seckillGoods.getStockCount(), seckillGoods.getId());
                    // 将当前商品id个数（库存量）放入队列中
                    redisTemplate.boundListOps("SeckillGoodsCountList_" + seckillGoods.getId()).leftPushAll(idArrays);

                    // 将当前商品对应的库存存储到redis中
                    redisTemplate.boundHashOps("SeckillGoodsCount").increment(seckillGoods.getId(), seckillGoods.getStockCount());

                }

            }
        }
    }

    /**
     * 获取当前id集合
     *
     * @param stockCount
     * @param id
     * @return
     */
    public Long[] pushId(Integer stockCount, Long id) {
        if (stockCount > 0) {
            Long[] ids = new Long[stockCount];
            for (int i = 0; i < stockCount; i++) {
                ids[i] = id;
            }
            return ids;
        }
        return null;
    }
}


